/* Copyright 2009 Palm, Inc.  All rights reserved. */

var PreflistAssistant = Class.create({

    initialize: function(args){
        if(args) {
			this.args=args;
		}
		this.carrier = $L('Carrier');
		this.carrierOnlyLabel = $L("#{carrier} Only").interpolate({carrier:this.carrier});
		this.platformQueryReq = TelephonyService.platformQuery(this.savePhonePlatform.bind(this));
		this.carriernamereq = SystemService.getCarrierName(this.handleCarrierNameQuery.bind(this));
		this.networkSearchInitiated = false;
		
		this.loadNetworkList = this.loadNetworkList.bind(this);
		
    },
    
    setup: function(){
		
		//Spinners for CallForwarding, Security and Network List.    
		this.spinnerLAttrs = {
			spinnerSize: Mojo.Widget.spinnerSmall
		};
		
		this.spinnerModel = {
			spinning: false
		};
		
		this.spinnerlockSIMModel = {
			spinning: true
		};
		
		this.spinnerVoicemailModel = {
			spinning: false
		};
		
		this.spinnernetworkListModel = {
			spinning: false
		};
		
		this.spinnerPRLModel = {
			spinning: false
		};
		
		this.spinnerProvisioningModel = {
			spinning: false
		};
		
		this.spinnerBAttrs = {
			spinnerSize: Mojo.Widget.spinnerLarge
		};
		
		this.spinnerInitialQueryModel = {
			spinning: false
		};
		
		
		this.voicemailbuttonModel = {
			buttonLabel: $L('Reset Voicemail Count'),
			disabled: false
		};
		
		this.controller.setupWidget('voicemailclear', this.buttonAttributes, this.voicemailbuttonModel);
		this.controller.listen('voicemailclear', Mojo.Event.tap, this.handleTapOnVoicemailReset.bind(this));
		
		this.controller.setupWidget('callforward-spinner', this.spinnerLAttrs, this.spinnerModel);
		
		this.controller.setupWidget('locksim-spinner', this.spinnerLAttrs, this.spinnerlockSIMModel);
		this.controller.setupWidget('networklist-spinner', this.spinnerLAttrs, this.spinnernetworkListModel);
		this.controller.setupWidget('PRL-spinner', this.spinnerLAttrs, this.spinnerPRLModel);
		this.controller.setupWidget('user-spinner', this.spinnerLAttrs, this.spinnerProvisioningModel);
		this.controller.setupWidget('vm-spinner', this.spinnerLAttrs, this.spinnerVoicemailModel);
		this.controller.setupWidget('initial-query-spinner', this.spinnerBAttrs, this.spinnerInitialQueryModel);
		
		//Call Forwarding
		this.dsAttributes = {
		hintText: $L('Enter number'),
		modelProperty: 'number',
		multiline: false,
		modifierState: Mojo.Widget.numLock,
		limitResize: false,
		enterSubmits: false,
		tapHoldToEnable:true,
		focusMode: Mojo.Widget.focusInsertMode,
		disabledProperty: 'p',
		changeOnKeyPress: false
		};
		this.callFWDNumbermodel = {
		        p: false,
		        'number': ''
		};
		this.controller.setupWidget('callforward-number', this.dsAttributes, this.callFWDNumbermodel);
		
		//Hide the Row until we get the response from network
		$('callfwdfirstrow').hide();
		$('callfwdlastrow').hide();
		$('callWaitingRowStatus').hide();
		$('showOutgoingCallerIDRowStatus').hide();
				
		
        this.showContactMatchModel = {
			value: true
		};
		       
        this.callFwdModel = {
			value: false
		};
		
        this.showOutgoingCallerIDModel = {
            value: true,
			disabled:false
        };
        this.callWaitingModel = {
            value: true
        };
        this.internationalDialingModel = {
            value: false
        };
        this.fdnModel = {
            value: false,
			disabled: false
        };
      
	    this.toggleNetworkAutoSelectModel = {
			disabled:true,
            value: true
        };
        this.ttyModel = {
            value: true
        };
		this.hacModel = {
            value: false
        };
        this.toggleWANModel = {
            value: true
        };
		
		this.toggleManualDataSettingsModel = {
			value: false
		};
		
		this.controller.setupWidget('showContactMatch', {
            modelProperty: 'value'
        }, this.showContactMatchModel);
        this.controller.get('showContactMatch').addEventListener(Mojo.Event.propertyChange, this.doPropertyChanged.bindAsEventListener(this, 'showContactMatch'));

		this.controller.setupWidget('callfwd', {
            modelProperty: 'value'
        }, this.callFwdModel);
        this.controller.get('callfwd').addEventListener(Mojo.Event.propertyChange, this.doPropertyChanged.bindAsEventListener(this, 'callfwd'));
        
        this.controller.setupWidget('showOutgoingCallerID', {
            modelProperty: 'value'
        }, this.showOutgoingCallerIDModel);
        this.controller.get('showOutgoingCallerID').addEventListener(Mojo.Event.propertyChange, this.doPropertyChanged.bindAsEventListener(this, 'showOutgoingCallerID'));
        
        this.controller.setupWidget('callWaiting', {
            modelProperty: 'value'
        }, this.callWaitingModel);
        this.controller.get('callWaiting').addEventListener(Mojo.Event.propertyChange, this.doPropertyChanged.bindAsEventListener(this, 'callWaiting'));
        
		this.controller.setupWidget('internationalDialingToggle', {
            modelProperty: 'value'
        }, this.internationalDialingModel);
        this.controller.get('internationalDialingToggle').addEventListener(Mojo.Event.propertyChange, this.doPropertyChanged.bindAsEventListener(this, 'internationalDialingToggle'));
		
		
		this.textAttributes = {
			enterSubmits: true,
			focus: false,
			multiline: false,       
			modifierState: Mojo.Widget.numLock,
			focusMode: Mojo.Widget.focusSelectMode,
			maxLength: 40,
			modelProperty: "number",
			disabledProperty: 'DISABLED'
		};
		this.voiceNumberModel = {
			'DISABLED':false,
	        'number': $L('Waiting for network')
		};

		this.controller.setupWidget('vmdatafield', this.textAttributes, this.voiceNumberModel);	
		this.controller.listen('vmdatafield', Mojo.Event.propertyChange, this.voicemailChangeHandler.bind(this));

		//*************Sam, patch start for IP dial************
		this.controller.setupWidget('ipd-spinner', this.spinnerLAttrs, {
			spinning: false
		});
		
		this.ipDialingPrefixNumberAttributes = {
			enterSubmits: true,
			focus: false,
			multiline: false,       
			modifierState: Mojo.Widget.numLock,
			focusMode: Mojo.Widget.focusSelectMode,
			maxLength: 40,
			modelProperty: "number",
			disabledProperty: 'DISABLED',
			charsAllow: Mojo.Widget.numericValidation,
		};
		this.ipDialingPrefixNumberModel = {
				'DISABLED':false,
				'number': $L('')
		};
		this.controller.setupWidget('ipdprefixfield', this.ipDialingPrefixNumberAttributes, this.ipDialingPrefixNumberModel);	
		this.controller.listen('ipdprefixfield', Mojo.Event.propertyChange, this.ipDialingPrefixChangeHandler.bind(this));
		//*************Sam, patch end for IP dial  ************
		this.controller.get('vmList').hide();
		
		this.controller.setupWidget('dtmfSelector', {
            choices: this.dtmfTones,
            modelProperty: 'currentTone'
        }, this.dtmfTonesModel);
        this.controller.get('dtmfSelector').addEventListener(Mojo.Event.propertyChange, this.dtmfToneChanged.bindAsEventListener(this));
        
        //DIALING SHORTCUTS
        //
        this.dialingShortcutsList = [];
        this.dialingShortcutsModel = {
            listTitle: $L("Dialing shortcuts"),
            items: this.dialingShortcutsList
        };
        this.controller.setupWidget('dialingShortcutsList', {
            itemTemplate: 'preflist/dialingshortcutitem',
            listTemplate: 'preflist/listcontainer',
            addItemLabel: $L("Add new number"),
            swipeToDelete: true
        }, this.dialingShortcutsModel);
        this.controller.get('dialingShortcutsList').addEventListener(Mojo.Event.listAdd, this.addDialingShortcut.bindAsEventListener(this));
        this.controller.get('dialingShortcutsList').addEventListener(Mojo.Event.listDelete, this.deleteDialingShortcut.bindAsEventListener(this));
        
        
        //SECURITY
        //
        this.controller.setupWidget('fdn', {
            modelProperty: 'value'
        }, this.fdnModel);
        this.controller.get('fdn').addEventListener(Mojo.Event.propertyChange, this.doPropertyChanged.bindAsEventListener(this, 'fdn'));
        
		this.controller.setupWidget('toggleDataRoaming', {
		    labelPlacement: Mojo.Widget.labelPlacementLeft,
			label: $L('Data Roaming'),
            choices: this.dataRoamingChoices,
            modelProperty: 'currentDataRoaming'
        }, this.dataRoamingModel);
        this.controller.get('toggleDataRoaming').addEventListener(Mojo.Event.propertyChange, this.doPropertyChanged.bindAsEventListener(this,'toggleDataRoaming'));
		
		this.ratChoices = [
			{label: $L("2G only"), value: "gsm"},
			{label: $L("3G only"), value: "umts"},
			{label: $L("Automatic"), value: "automatic"}
		];
		
		this.ratModel = {
			currentRat: "automatic"
		};
		
		this.controller.setupWidget('toggleRat', {
			label: $L('Network Type'),
            choices: this.ratChoices,
            modelProperty: 'currentRat'
        }, this.ratModel);
        this.controller.get('toggleRat').addEventListener(Mojo.Event.propertyChange, this.doPropertyChanged.bindAsEventListener(this,'toggleRat'));
		
		this.voiceRoamingChoices =  [
			{label: this.carrierOnlyLabel,value: "homeonly"},
			{label : $L("Automatic"),value: "any"}
		];
	
		this.voiceRoamingModel = {
			currentVoiceRoaming: "homeonly"			
		};

		this.controller.setupWidget('toggleVoiceRoaming', {
		    labelPlacement: Mojo.Widget.labelPlacementLeft,
			label: $L('Voice Network'),
            choices: this.voiceRoamingChoices,
            modelProperty: 'currentVoiceRoaming'
        }, this.voiceRoamingModel);
        this.controller.get('toggleVoiceRoaming').addEventListener(Mojo.Event.propertyChange, this.doPropertyChanged.bindAsEventListener(this,'toggleVoiceRoaming'));
        		
        this.controller.setupWidget('toggleNetworkAutoSelect', {
            modelProperty: 'value'
        }, this.toggleNetworkAutoSelectModel);
        this.controller.get('toggleNetworkAutoSelect').addEventListener(Mojo.Event.propertyChange, this.doPropertyChanged.bindAsEventListener(this, 'toggleNetworkAutoSelect'));
		
		this.controller.setupWidget('toggleManualDataSettings', {
            modelProperty: 'value'
        }, this.toggleManualDataSettingsModel);
        this.controller.get('toggleManualDataSettings').addEventListener(Mojo.Event.propertyChange, this.doPropertyChanged.bindAsEventListener(this, 'toggleManualDataSettings'));
		
        this.controller.get('reading_networklist_status').addEventListener(Mojo.Event.tap, this.networkNameTapHandler.bindAsEventListener(this));
		this.drawerModel = {myOpenProperty:false};
		this.controller.setupWidget('networkdetails', {modelProperty:'myOpenProperty'}, this.drawerModel);
		this.networkDetailsdrawer = this.controller.get('networkdetails');
		this.networkList = [];
		this.networkListModel = {items: this.networkList};

		this.controller.setupWidget('networklist', 
									{
										itemTemplate:'preflist/networklistitem',
										addItemLabel: $L("Search for networks")
									}, 
									this.networkListModel);	
		this.networkListWidget = this.controller.get('networklist');
		Mojo.Event.listen(this.networkListWidget, Mojo.Event.listAdd, this.networkListPrompt.bindAsEventListener(this));
		Mojo.Event.listen(this.networkListWidget, Mojo.Event.listTap, this.selectNetwork.bindAsEventListener(this));				
						
		$('reading_networklist_row').hide();
		
        
        //toggle switch is for TTY
        this.controller.setupWidget('toggleTTY', {
            modelProperty: 'value'
        }, this.ttyModel);
        this.controller.get('toggleTTY').addEventListener(Mojo.Event.propertyChange, this.doPropertyChanged.bindAsEventListener(this, 'toggleTTY'));
		
		this.controller.setupWidget('toggleHAC', {
            modelProperty: 'value'
        }, this.hacModel);
        this.controller.get('toggleHAC').addEventListener(Mojo.Event.propertyChange, this.doPropertyChanged.bindAsEventListener(this, 'toggleHAC'));
                
        //toggle switch is for WAN
        this.controller.setupWidget('toggleWAN', {
            modelProperty: 'value'
        }, this.toggleWANModel);
        this.controller.get('toggleWAN').addEventListener(Mojo.Event.propertyChange, this.doPropertyChanged.bindAsEventListener(this, 'toggleWAN'));

        $('security').observe(Mojo.Event.tap, this.doTap.bindAsEventListener(this));
		$('provisioning').observe(Mojo.Event.tap, this.doTap.bindAsEventListener(this));
		$('PRL').observe(Mojo.Event.tap, this.doTap.bindAsEventListener(this));
		$('manualdatasettings').observe(Mojo.Event.tap, this.doTap.bindAsEventListener(this));
		$('internationalDialingRegionRow').observe(Mojo.Event.tap, this.doTap.bindAsEventListener(this));
		
		this.controller.listen('callforward-number', Mojo.Event.propertyChange, this.callFWDNumChanged.bind(this));
		
		//Hide Platform Specific Items until we figure out the platform type.
        this.hidePlatformSpecificItems();
		
		//Get the Intial Values
		//this.getInitialValues(); 
		
		//hide phoneNumber before get the number since for some sim card it is not available
		$('phoneNumberGroup').hide(); 
		
		// App Menu - Remove default items and add only Edit & Help items.
		var appMenuModel = {
	        visible: true,
            items: [Mojo.Menu.editItem, {label:$L('Help'), command:Mojo.Menu.helpCmd}]
        };
		this.controller.setupWidget(Mojo.Menu.appMenu, {omitDefaultItems:true}, appMenuModel);
		
		this.showFDNErrorMethod = this.showFDNError.bindAsEventListener(this);
		this.showCallIDErrorMethod = this.showCallIDError.bindAsEventListener(this);
		this.showCallWaitingErrorMethod = this.showCallWaitingError.bindAsEventListener(this);
		
		this.controller.get('scrim').hide();
		this.controller.get('phoneOffText').hide();
		if (this.args && this.args.type) {
			this.handleExternalLaunch(this.args,true);
		}
    },	
		
	activate: function(args){
		this.hasPincodeScene=false;
		if(args && args.type) {//relaunch app from external launch, and there is other sece on top of preflist scene
			this.handleExternalLaunch(args);
		}
		
		if(this.updateCallsList === true){
			this.updateCallsList = false;
			this.spinnerInitialQueryModel.spinning = true;
			this.controller.modelChanged(this.spinnerInitialQueryModel);
			this.controller.get('scrim').show();
			this.updateCalls.bind(this).delay(10);
		}
     },
	 
	 cleanup: function() {
	 	// cancel network list query in case there's one pending
		// calling when one isn't pending is claimed to be harmless
	 	TelephonyService.networkListQueryCancel();
	 },
	
	updateCalls: function(){
		this.spinnerInitialQueryModel.spinning = false;
		this.controller.modelChanged(this.spinnerInitialQueryModel);
		this.controller.get('scrim').hide();
		this.controller.get('phoneOffText').hide();
		this.forwardQueryReq = TelephonyService.forwardQuery('unconditional', this.callFwdQueryDone.bind(this));
		this.callWaitingQueryReq = TelephonyService.callWaitingQuery(this.updateCallWaiting.bind(this));
		this.clirQueryReq = TelephonyService.clirQuery(this.updateOutgoingCallerID.bind(this));		
	},
	
	handleCommand: function(event) {
		if (event.type == Mojo.Event.command) {
			if (event.command == Mojo.Menu.helpCmd) {
				var r = new Mojo.Service.Request('palm://com.palm.applicationManager', {
					method: 'open',
					parameters: {'id': 'com.palm.app.help',params: {'target': 'http://help.palm.com/phone/phone_prefs/index.html'}}});
			}
		}
	},	
	
	getInitialValues: function() {
		this.spinnerModel.spinning = true;
		this.controller.modelChanged(this.spinnerModel);
		this.getPhoneNumberReq = TelephonyService.phoneNumberQuery(this.phoneNumberQueryDone.bind(this));
		this.ttyQueryReq = TelephonyService.ttyQuery(this.updateTTY.bind(this));
		this.hacQueryReq = TelephonyService.hacQuery(this.updateHAC.bind(this));

		this.getShortCutNumbersReq = SystemService.getShortCutNumbers(this.loadDialingShortcuts.bind(this));
        this.getRoamguardServiceReq = SystemService.getRoamguardService(this.updateDataRoaming.bind(this));               
		this.getSystemPreferencesServiceReq = SystemService.getSystemPreferencesService(
			['phoneInternationalDialingActive', 'phoneInternationalDialingRegionId'],this.updateInternationalDialingSettings.bind(this));
		this.networkStatusQueryReq = TelephonyService.networkStatusQuery(this.updateNetworkname.bind(this));
        this.getSystemPreferencesServiceShowcontactmatchReq = SystemService.getSystemPreferencesService('showcontactmatch',this.updateShowcontactmatch.bind(this));
		this.updateManualDataSettingsReq = SystemService.getManualDataSettings(this.updateManualDataSettings.bind(this));
		this.getVoiceNumberEditableReq = SystemService.getSystemPreferencesService('allowEditVoicemail',this.updateVoicenumberEditableQueryDone.bind(this));
		this.getBandSelectionAllowed = SystemService.getSystemPreferencesService('hideRatSelection',this.updateRatSelection.bind(this));
        this.getSystemPreferencesNetworkSettingReq = SystemService.getSystemPreferencesService(['showUpdateNetworkSettings','showUpdatePRL'],this.updateNetworkSettingDone.bind(this));
		this.WANQueryReq = SystemService.getWANStatus(this.updateWAN.bind(this));
		//*************Sam, patch start for IP dial************
		SystemService.getSystemPreferencesService('ipDialingPrefixNumber',this.updateIpDialingPrefixDone.bind(this));
		//*************Sam, patch end for IP dial  ************
	},
	
	savePhonePlatform: function(payload) {
		this.phoneType = '';
		
		this.powerQueryReq = TelephonyService.powerQuery(this.powerQueryDone.bind(this));
		
		if(!payload.returnValue) {
			return;
		}
		
		if(!payload.extended.platformType) {
			return;
		}
		
		this.phoneType = payload.extended.platformType;
	},
	
	powerQueryDone: function(payload) {
		
		this.phoneRadio = false;
		if(payload) {
			if (payload.extended) {
				if (payload.extended.powerState == 'on') {
					this.phoneRadio = true;
					this.doInit();
				}
				else {
					this.phoneRadio = false;            	
				}
			}
			else if(payload.eventPower) {
				if (payload.eventPower == 'on') {
					this.phoneRadio = true;
					this.spinnerInitialQueryModel.spinning = true;
					this.controller.modelChanged(this.spinnerInitialQueryModel);
					this.controller.get('scrim').show();
					this.doInit.bind(this).delay(10);
				}
				else {
					this.phoneRadio = false;	
				}
			}
        }
		
		if(!this.phoneRadio) {
			this.controller.get('phonepref').hide();
			if (this.cancelable !== undefined) {
				Mojo.Controller.appController.showBanner(
					{
						icon: "images/notification-small-handset.png",
						messageText: $L("Settings updated"),
						soundClass: 'none'
					}, 
				{},'');
				$('phoneOffText').innerHTML = $L("Reading settings...");
			} else {
				$('phoneOffText').innerHTML = $L("You need a network connection to your wireless service provider to see Phone Preferences.");
			}
			this.controller.get('phoneOffText').show();
			this.controller.hideWidgetContainer(this.controller.get('phonepref'));
			this.controller.getSceneScroller().mojo.revealTop(0);
		}		
	},
	
	doInit: function() {
		this.spinnerInitialQueryModel.spinning = false;
		this.controller.modelChanged(this.spinnerInitialQueryModel);
		this.controller.get('scrim').hide();
		this.controller.get('phoneOffText').hide();
		this.getInitialValues();
		this.doPlatformSpecificSetup();
		this.controller.get('phonepref').show();
		
		this.controller.showWidgetContainer(this.controller.get('phonepref'));
	},
	
    hidePlatformSpecificItems: function(){
			
        if ($("cdma_dialing")) {
            $("cdma_dialing").hide();
			$("cdma_dialing_text").hide();
        }
		
		$('callforward-status').hide();
        if ($("gsm_security")) {
            $("gsm_security").hide();
        }
        if ($("network_selection")) {
            $("network_selection").hide();			
        }            
		
		if ($("ratRow")) {
			$("ratRow").hide();
		}
		
		if ($('voiceRoamingRow')) {
			$('voiceRoamingRow').hide();	
		}
		if ($('showOutgoingCallerIDRow')) {
			$('showOutgoingCallerIDRow').hide();
		}
		if($('callWaitingRow')) {
			$('callWaitingRow').hide();
		}
		//need check carrier also, since this is carrier only feature
		if($('provisioning')){
			$('provisioning').hide();
		}
		if($('PRL')){
			$('PRL').hide();
		}
		if($('voicemailclear')) {
			$('voicemailclear').hide();		
		}
		if($('hacRow')) {
			$('hacRow').hide();
		}
    },

	updateNetworkSettingDone: function(payload){
		if (payload && payload.showUpdateNetworkSettings == true) {
			this.showUpdateNetworkSettings = true;
			if (this.phoneType == 'cdma') {
				if ($('provisioning')) {
					$('provisioning').show();
				}
			}
		}
		
		if (payload && payload.showUpdatePRL == true) {
			this.showUpdatePRL = true;
			$('PRL').show();
		} else {
			this.showUpdatePRL = false;
			$('PRL').hide();
		}
	},
	
	updateDataRoamingVisibility: function(payload){
		if (payload && payload.hideDataRoaming == true) {
			$('dataroamingrow').hide();
		}
	},
	
	updateVoicenumberEditableQueryDone: function(payload){
		if (payload && payload.allowEditVoicemail == false) {
			this.voiceNumberModel.DISABLED = true;
			this.controller.modelChanged(this.voiceNumberModel, this);
		}
},    

    doPlatformSpecificSetup: function(){
		        
        if (this.phoneType == "gsm") {
			$('callforward-status').show();
			this.controller.get('vmList').show();
 			if ($('vm-spinner')) {
				this.spinnerVoicemailModel.spinning = true;
				this.controller.modelChanged(this.spinnerVoicemailModel);
			}
			
			//$('i18nDialing').removeClassName('unlabeled');
			this.fixedDialingQueryReq  = TelephonyService.fixedDialingQuery(this.updateFDN.bind(this));
	        this.pin1StatusReq =  TelephonyService.pin1Status(true, this.updateLockSIM.bind(this, false));

			this.getRatReq = TelephonyService.ratQuery(this.updateRat.bind(this));				
			this.networkIdQueryReq = TelephonyService.networkIdQuery(this.updateNetworkId.bind(this));
			this.updateManualNetworkAvailabilityReq = TelephonyService.manualNetworkSelectionPermittedQuery(this.updateManualNetworkAvailability.bind(this));
            this.networkSelectionModeQueryReq = TelephonyService.networkSelectionModeQuery(this.updateNetworkSelectionMode.bind(this));
       		this.getVoiceNumberReq = TelephonyService.voicemailNumberQuery(this.voiceNumberQueryDone.bind(this));

			this.callWaitingQueryReq = TelephonyService.callWaitingQuery(this.updateCallWaiting.bind(this));
			this.clirQueryReq = TelephonyService.clirQuery(this.updateOutgoingCallerID.bind(this));
			this.forwardQueryReq = TelephonyService.forwardQuery('unconditional', this.callFwdQueryDone.bind(this));
				
            if ($("gsm_security")) {
                $("gsm_security").show();
            }
	        
			//this will get updated with the correct text once pin1status returns
            if ($("lockSIM")) {
                $("lockSIM").hide();
            }
            if ($("changeSIMPIN")) {
                $("changeSIMPIN").hide();
            }
			if($("fdn")){
				$("fdn").hide();
			}
			if($("setfdn")) {
				$("setfdn").hide();
			}
			if($('changeFDNPIN')) {
				$('changeFDNPIN').hide();
			}
			
			if ($('manualdatasettingstogglerow')) {
				$('wantogglerow').removeClassName('last');
				$('manualdatasettingstogglerow').show();
			}
			
        }
        else {
            
            this.dtmfDurationQueryReq = TelephonyService.dtmfDurationQuery(this.updateDTMF.bind(this));
        	this.roamModeQueryReq = TelephonyService.roamModeQuery(this.updateVoiceRoaming.bind(this));
            
            if ($("cdma_dialing")) {
                $("cdma_dialing").show();
				//$("cdma_dialing_text").show();
            }            
			if ($('voiceRoamingRow')) {
				$('voiceRoamingRow').show();	
			}		
			if (this.showUpdateNetworkSettings == true) {
				if ($('provisioning')) {
					$('provisioning').show();
				}
			}
			
			if($('callfwdfirstrow')) {
				$('callfwdfirstrow').removeClassName('first');
				$('callfwdfirstrow').addClassName('single');
			}
			
			if ($('PRL') && this.showUpdatePRL == true) {
				$('PRL').show();
			} else {
				$('PRL').hide();
			}
			
			if($('voicemailclear')) {
				$('voicemailclear').show();	
			}
			this.initOnProvisionStart();
        }
        
    },
    //Phone Number
	phoneNumberQueryDone: function(payload){
		if (payload.returnValue == true && payload.extended){
			if (payload.extended.number !== "bad_file_on_sim") {
				$('phoneNumber').innerHTML = Mojo.Format.formatPhoneNumber(payload.extended.number);
				$('phoneNumberGroup').show();
			}
		}
	}, 
	
	//Handler for Carrier Name Query
	handleCarrierNameQuery: function(payload) {
		if(!payload){
			return;
		}
		if(payload.returnValue != undefined && payload.returnValue == true) {
			this.carrier =  $L(payload.longName);
			this.carrierOnlyLabel = $L("#{carrier} Only").interpolate({carrier:this.carrier});
			this.voiceRoamingChoices[0].label = this.carrierOnlyLabel;
			this.controller.modelChanged(this.voiceRoamingModel);
		}
	} ,

	//Voicemail Number
	voiceNumberQueryDone: function(payload){
		

		if (payload.returnValue == true && payload.extended) {
			this.voiceNumber = payload.extended.number;
			this.voiceNumberModel.number = Mojo.Format.formatPhoneNumber(this.voiceNumber);
			this.controller.modelChanged(this.voiceNumberModel, this);
			if ($('vm-spinner')) {
				this.spinnerVoicemailModel.spinning = false;
				this.controller.modelChanged(this.spinnerVoicemailModel);
			}
		}
		else{//failed to get voicemail number
			TelephonyService.voicemailNumberQueryCarrierDb(this.voiceNumberQueryDoneCarrierDb.bind(this));
		}
		
	},
	
	voiceNumberQueryDoneCarrierDb: function(success, number) {
		if ($('vm-spinner')) {
			this.spinnerVoicemailModel.spinning = false;
			this.controller.modelChanged(this.spinnerVoicemailModel);
		}

		if (success && number) {
			this.voiceNumber = number;
			this.voiceNumberModel.number = Mojo.Format.formatPhoneNumber(this.voiceNumber);
			this.controller.modelChanged(this.voiceNumberModel, this);
		} else{//failed to get voicemail number
			this.voiceNumberModel.number = $L("Unable to access voicemail number.");
			this.controller.modelChanged(this.voiceNumberModel, this);
		}
		
	},

voicemailChangeHandler: function(event) {
	var newValue = event.value;
	if(newValue && newValue !== this.voiceNumber) {
		newValue = this.normalizeNumber(newValue);
		if (newValue.length > 0) {
			this.preVoiceNumber = this.voiceNumber;
			this.voiceNumber = newValue;
			this.setVoiceNumberReq = TelephonyService.voicemailNumberSet(this.voiceNumber, this.voiceNumberSetDone.bind(this));
		}
	}
	this.voiceNumberModel.number = Mojo.Format.formatPhoneNumber(this.voiceNumber);
	this.controller.modelChanged(this.voiceNumberModel, this);
},

//*************Sam, patch start for IP dial************
ipDialingPrefixSetDone: function(payload){
	if (!payload || !payload.returnValue) {//failed to set ip dialing prefix number, update with old one
		this.ipDialingPrefixNumber = this.preIpDialingPrefixNumber;
		this.ipDialingPrefixNumberModel.number = this.ipDialingPrefixNumber;
		this.controller.modelChanged(this.ipDialingPrefixNumberModel, this);
	}
},

ipDialingPrefixChangeHandler: function(event) {
	var newValue = event.value ? event.value : "";
	if(newValue !== this.ipDialingPrefixNumber) {
		this.preIpDialingPrefixNumber = this.ipDialingPrefixNumber;
		this.ipDialingPrefixNumber = newValue;
		SystemService.setSystemPreferencesService("ipDialingPrefixNumber", newValue, this.ipDialingPrefixSetDone.bind(this));
	}
},

updateIpDialingPrefixDone: function(payload) {
	this.preIpDialingPrefixNumber="";
	this.ipDialingPrefixNumber="";

	if (payload && payload.returnValue && payload.ipDialingPrefixNumber) {
		this.ipDialingPrefixNumber=payload.ipDialingPrefixNumber;
		this.ipDialingPrefixNumberModel.number = payload.ipDialingPrefixNumber;
		this.controller.modelChanged(this.ipDialingPrefixNumberModel, this);
	} 
}, 
//*************Sam, patch end for IP dial  ************

isValidDialKey: function(key){
    for (i = 0; i < key.length; i++) {
		if (!((key[i] >= '0' && key[i] <= '9') 
			|| key[i] == '*' || key[i] == '#'
			|| key[i] == 'w' || key[i] == 'p' 
			|| key[i] == '+')) {
            return false;
		}
	}
    return true;    
},

// strips characters that aren't valid for dialing at all
	normalizeNumber: function(number) {
		var validDigits = "+01234567890*#pwt";
		
		var out = "";
		for (var i = 0; i < number.length; i++) {
			var curDigit = number.charAt(i);
			if (validDigits.indexOf(curDigit) >= 0) {
				out += curDigit;
			}
		}
		
		// numbers starting with p or w aren't valid
		if (out.length > 0) {
			var firstDigit = out.charAt(0);
			switch (firstDigit) {
				case 'p':
				case 'w':
				case 't':
					return "";
			}
		}
		
		return out;
	},

voiceNumberSetDone: function(payload){
	if (!payload.returnValue) {//failed to set voicemail number, update with old voiceNumber
		this.voiceNumber = this.preVoiceNumber;
		this.voiceNumberModel.number = Mojo.Format.formatPhoneNumber(this.voiceNumber);
		this.controller.modelChanged(this.voiceNumberModel, this);
	}
},

	//CALLFORWARDING     
    callFwdQueryDone: function(payload) {
		
		this.spinnerModel.spinning = false;
		this.controller.modelChanged(this.spinnerModel);
		var errorImageContent;
		
		this.callFwdQueryError = false;
		
		if(!payload.returnValue) {
			
			this.callFwdQueryError = true;
			this.controller.stopListening($('callforward-status'), Mojo.Event.tap, this.showFDNErrorMethod);
			if (payload.errorCode && payload.errorCode === 108) {
				payload.errorImage = "images/lock.png";
			}
			else {
				payload.errorImage = "images/warning-icon.png";
				this.updateCallsList = true;
			}
			
			payload.errorText = $L('Call forwarding');
			this.CFErrorCode = payload.errorCode;
			
			this.controller.listen($('callforward-status'), Mojo.Event.tap, this.showFDNErrorMethod);
		
				errorImageContent = Mojo.View.render({
			 		object: payload,
		           template: 'preflist/networkrestrictimage'
		      });
			 
			 $('callforward-status').innerHTML = errorImageContent;
			 $('callfwdfirstrow').hide();
			 $('callfwdlastrow').hide();
			 $('callforward-status').show();
			return;
		}
	
		// search through status array for voice and default bearers
		if (payload.extended.status != null) {
			var status = payload.extended.status;
			var found = false;
			for (var i = 0; i < status.length; i++) {
				
				switch (status[i].bearer) {
					case 'voice':
					case 'default':
					case 'defaultbearer':
						if (status[i].activated) {
							found = true;
							this.callFWDNumbermodel.number = status[i].number;
							this.callFwdModel.value = true;				
							this.controller.modelChanged(this.callFWDNumbermodel);			
							$('callfwdlastrow').show();
							this.controller.showWidgetContainer(this.controller.get('callfwdlastrow'));
						}
						else {
							if(status[i].number) {
								this.callFWDNumbermodel.number = status[i].number;
								this.controller.modelChanged(this.callFWDNumbermodel);
							}
						}
						break;		
					default:
						break;
				}
				if (found){
					break;
				}
			}
			if (!found) {
				this.callFwdModel.value = false;	
			}
		} else {
				this.callFwdModel.value = false;			
			}
			this.controller.modelChanged(this.callFwdModel);
			$('callforward-status').hide();
			$('callfwdfirstrow').show();
			
	},
	
	callFWDNumChanged: function(event) {
		
		if(!event.value) {	
			return;
		}
		this.forwardRegisterReq = TelephonyService.forwardRegister('unconditional', event.value, this.callFwdSet.bind(this));
	},
	
	callFwdSet: function(payload) {
		if(!payload.returnValue) {
			if (payload.errorCode && payload.errorCode === 108) {
				this.showFDNError(payload.errorCode);
			}
			else {
				if (Messages.serviceErrors[payload.errorCode] !== undefined) {
					payload.errorText = Messages.serviceErrors[payload.errorCode].toString();
				}
				else {
					payload.errorText = Messages.serviceErrors[Messages.defaultErrorIndex].toString();
				}
				this.showErrorDialog(payload.errorText);
			}
			
		}
	},
	
	//Show the FDN Restricted Error Message
	showFDNError: function(event,errorCode) {
		
		switch(errorCode || this.CFErrorCode) {
			case 108: this.showErrorDialog($L('While fixed dialing is enabled, call forwarding cannot be set.'));
					  break;
			case 102: this.showErrorDialog($L('You need a network connection to your wireless service provider to see some settings.'));
					  break;
			default:  if (Messages.serviceErrors[errorCode] !== undefined) 
						this.showErrorDialog(Messages.serviceErrors[errorCode].toString());
					  else 
					    this.showErrorDialog(Messages.serviceErrors[Messages.defaultErrorIndex].toString());
					  break;
		}
		 
	},
	
	showErrorDialog: function(msg) {
		
		if (!msg || msg === " ") {
			return;
		}
		
		this.controller.showAlertDialog({
	    onChoose: function(value) {},
	    message: msg,
	    choices:[
        {label: $L('OK'), value:'dismissed'}    
	    ]
	  });
	},
	
	//Show Caller ID    
    updateOutgoingCallerID: function(payload){
		if (payload.returnValue && payload.extended) {
			this.showOutgoingCallerIDModel.value = !payload.extended.restricted;
			if(payload.extended.permanent != undefined && payload.extended.permanent === true) {
				this.showOutgoingCallerIDModel.disabled = true;
			}
			this.controller.modelChanged(this.showOutgoingCallerIDModel);
			$('showOutgoingCallerIDRow').show();
			$('showOutgoingCallerIDRowStatus').hide();
		}
		else {
			this.controller.stopListening($('showOutgoingCallerIDRowStatus'), Mojo.Event.tap, this.showCallIDErrorMethod);
			if (payload.errorCode && payload.errorCode === 108) {
				payload.errorImage = "images/lock.png";
			}
			else {
				payload.errorImage = "images/warning-icon.png";	
				this.updateCallsList = true;
				}
			this.callerIDErrorCode = payload.errorCode;
			this.controller.listen($('showOutgoingCallerIDRowStatus'), Mojo.Event.tap, this.showCallIDErrorMethod);
			payload.errorText = $L('Show my caller ID');
				errorImageContent = Mojo.View.render({
			 		object: payload,
		           template: 'preflist/networkrestrictimage'
		      });
			 $('showOutgoingCallerIDRow').hide();
			 $('showOutgoingCallerIDRowStatus').innerHTML = errorImageContent;
			 $('showOutgoingCallerIDRowStatus').show();
			return;
			
		}
    },
	
	showCallIDError: function(event,errorCode) {
		switch(errorCode || this.callerIDErrorCode) {
			case 108: this.showErrorDialog($L('While fixed dialing is enabled, caller ID cannot be set.'));
					  break;
			case 102: this.showErrorDialog($L('You need a network connection to your wireless service provider to see some settings.'));
					  break;
			default:  if (Messages.serviceErrors[errorCode] !== undefined) 
						this.showErrorDialog(Messages.serviceErrors[errorCode].toString());
					  else 
					    this.showErrorDialog(Messages.serviceErrors[Messages.defaultErrorIndex].toString());
					  break;
		}
		
	},
    
	//Call Waiting
    updateCallWaiting: function(payload){
		var errorImageContent;
		if(payload.returnValue && payload.extended) {
			this.callWaitingModel.value = payload.extended.enabled;
        	this.controller.modelChanged(this.callWaitingModel);
			$('callWaitingRow').show();
			$('callWaitingRowStatus').hide();
		}
		else {
			this.controller.stopListening($('callWaitingRowStatus'), Mojo.Event.tap, this.showCallWaitingErrorMethod);
			if (payload.errorCode && payload.errorCode === 108) {
				payload.errorImage = "images/lock.png";
			}
			else {
				payload.errorImage = "images/warning-icon.png";
				this.updateCallsList = true;
				}
			this.controller.listen($('callWaitingRowStatus'), Mojo.Event.tap, this.showCallWaitingErrorMethod);
			this.callWaitingErrorCode = payload.errorCode;
			payload.errorText = $L('Call waiting');
				errorImageContent = Mojo.View.render({
			 		object: payload,
		           template: 'preflist/networkrestrictimage'
		      });
			 $('callWaitingRowStatus').innerHTML = errorImageContent;
			 $('callWaitingRow').hide();
			$('callWaitingRowStatus').show();
			return;
		} 
    },
	
	showCallWaitingError: function(event,errorCode) {
		switch(errorCode || this.callerIDErrorCode) {
			case 108: this.showErrorDialog($L('While fixed dialing is enabled, call waiting cannot be set.'));
					  break;
			case 102: this.showErrorDialog($L('You need a network connection to your wireless service provider to see some settings.'));
					  break;
			default:  if (Messages.serviceErrors[errorCode] !== undefined) {
						this.showErrorDialog(Messages.serviceErrors[errorCode].toString());
					  } else { 
					    this.showErrorDialog(Messages.serviceErrors[Messages.defaultErrorIndex].toString());
					}  
					break;
		}
	},
	    
	//Showcontactmatch
    updateShowcontactmatch: function(payload){
		if(payload.showcontactmatch == undefined)
			return;
        this.showContactMatchModel.value = payload.showcontactmatch;
        this.controller.modelChanged(this.showContactMatchModel);
        
    },
	
	
	
	//DTMF
    updateDTMF: function(payload){
		
		if(!payload.returnValue)
			return;
			
       this.dtmfTonesModel.currentTone = payload.extended.dtmflong ? "true" : "false"
       this.controller.modelChanged(this.dtmfTonesModel);
    },
	
	 dtmfToneChanged: function(event){
		if(!event.value)
			return;
		
       this.dtmfDurationSetReq = TelephonyService.dtmfDurationSet(event.value == "true" ? true : false);
     },
    
	
	//Network Selection
	
	// if network blocks manual network selection, don't show controls
	updateManualNetworkAvailability: function(enabled) {
		if (enabled) {
			this.manualNetworkAvailable = true;
			if ($("network_selection")) {
                $("network_selection").show();
            }
		} else {
			this.manualNetworkAvailable = false;
			$("network_selection").hide();
		}
	},
	
	networkNameTapHandler: function(event) {
		// don't respond to taps if manual network selection isn't available
		if (this.manualNetworkAvailable == false) {
			return;
		}
		this.networkDetailsdrawer.mojo.getOpenState() ? this.toggleNetworkListDrawer(false) : this.toggleNetworkListDrawer(true);			
	},
	
	toggleNetworkListDrawer: function(drawerOpen, skipUpdate) {
										
		if(this.networkDetailsdrawer.mojo.getOpenState() === drawerOpen)
			return;
		
		if (this.networkDetailsdrawer.mojo.getOpenState()) 		
			this.controller.hideWidgetContainer(this.networkDetailsdrawer);	
		else
			this.controller.showWidgetContainer(this.networkDetailsdrawer);
			
		this.networkDetailsdrawer.mojo.setOpenState(!this.networkDetailsdrawer.mojo.getOpenState());
		
		if (!drawerOpen) {
			// cancel network list query in case there's one pending
			// calling when one isn't pending is claimed to be harmless
			TelephonyService.networkListQueryCancel();
		}
		if (!skipUpdate)
			this.networkSelectionModeQueryReq = TelephonyService.networkSelectionModeQuery(this.updateNetworkSelectionMode.bind(this));		
	},
	
	updateNetworkId: function(payload) {
		if(!payload.returnValue)
			return;
		if(payload.mccmnc) {
			this.currentNetworkId = payload.mccmnc;			
		}
	},
		 
    updateNetworkSelectionMode: function(payload){
		if(!payload.returnValue)
			return;
		if(payload.automatic != null) {
			if (payload.automatic) {
				this.toggleNetworkAutoSelectModel.value = payload.automatic;
				$('networknamerow').show();	
				this.networkDetailsdrawer.mojo.setOpenState(false);
				this.controller.hideWidgetContainer(this.networkDetailsdrawer);
				$('reading_networklist_row').hide();
									
			}
			else {
				this.toggleNetworkAutoSelectModel.value = payload.automatic;
				this.toggleNetworkListDrawer(true, true);	
				$('reading_networklist_row').show();
				$('networknamerow').hide();											
			}
			this.toggleNetworkAutoSelectModel.disabled = false;
			this.controller.modelChanged(this.toggleNetworkAutoSelectModel);
			this.automaticSelectionActive = payload.automatic; 			
		}
    },
	
	// before searching for networks, prompt to confirm disconnecting data network is okay
	networkListPrompt: function() {
		// if data is blocked, don't bother asking if it's okay to turn it off
		if (this.toggleWANModel.value == false) {
			this.onNetworkListPromptChoice("OK");
			return;
		}
		
		this.controller.showAlertDialog({
            	onChoose: this.onNetworkListPromptChoice.bind(),
            	message: $L("Searching for networks will temporarily disconnect your data connection."),
				choices: [
					{
                		label: $L('Search for networks'),
						type: 'affirmative',
                		value: 'OK'
            		}, {
                		label: $L('Cancel'),
						type: 'dismiss',
                		value: 'CANCEL'
            		}
				]
        });
    },
	
	// if okay, proceed to load; otherwise, restore network selection list with current value
	onNetworkListPromptChoice: function(choice) {
		if (choice === 'OK') {
			this.loadNetworkList();	
		} else {
			this.networkSelectionModeQueryReq = TelephonyService.networkSelectionModeQuery(this.updateNetworkSelectionMode.bind(this));
		}
	},
	
    loadNetworkList: function(){
        if (this.phoneType == "gsm") {
			this.networkSearchInitiated = true;
			this.networkListQueryReq = TelephonyService.networkListQuery(this.updateNetworkList.bind(this));
			
			this.networkListBusy($L("Searching for networks"));
		}
    },
    
	networkListBusy: function(statusText) {
		$('reading_networklist_row').show();
		//this.controller.stopListening($('reading_networklist_status'), Mojo.Event.tap, this.loadNetworkList);
		$('reading_networklist_status').innerHTML = statusText;
		
		//only enable the spinner on the second row of the table		
		if ($('networklist-spinner')) {
			this.spinnernetworkListModel.spinning = true;
			this.controller.modelChanged(this.spinnernetworkListModel);
		}
	},
	
	networkListBusyOff: function(statusText) {
		if ($('networklist-spinner')) {
           this.spinnernetworkListModel.spinning = false;
		   this.controller.modelChanged(this.spinnernetworkListModel);
        }
		
		$('reading_networklist_status').innerHTML = statusText;
	},
	
    updateNetworkList: function(payload){		
    	
			
		if(!payload.returnValue) {
			if (Messages.serviceErrors[payload.errorCode] !== undefined) {
				payload.errorText = Messages.serviceErrors[payload.errorCode].toString();
			} else {
				payload.errorText = Messages.serviceErrors[Messages.defaultErrorIndex].toString();
			}
			 var errorImageContent = Mojo.View.render({
			 		object: payload,
		           template: 'preflist/networkerrorimage'
		      });
			 this.networkListBusyOff(errorImageContent);
			//this.controller.listen($('reading_networklist_status'), Mojo.Event.tap, this.loadNetworkList);

			return;
		}
		
		var networks = payload.extended.networks;
		var networkDrawerToggleText = '';
		if (networks && networks.length > 0) {
			this.toggleNetworkListDrawer(true, true);						
			this.networkList.clear();
			var index = 0;
			networks.each((function(networkItem){
				
				if(this.networkList && this.networkList.length > 0) {
					for(var i=0; i<this.networkList.length; i++) {
						if(this.networkList[i].networkId === networkItem.id)
							return;
					}
				}
				
				if(this.automaticSelectionActive === false && networkItem.id === this.currentNetworkId) {
					this.networkList.push({
						networkListName: networkItem.name,
						networkId: networkItem.id,
						checkMark: 'checkmark'					
					})
					networkDrawerToggleText = networkItem.name.escapeHTML();
				}
				else {
					this.networkList.push({
						networkListName: networkItem.name,
						networkId: networkItem.id,
						checkMark: ''					
					})
				}				
			}).bind(this))
			this.controller.modelChanged(this.networkListModel);
			if (this.automaticSelectionActive === true) {
				networkDrawerToggleText = $L("Available networks");
			} 
		} else {
			networkDrawerToggleText = $L('No networks available');
			
		}
		
		this.networkListBusyOff(networkDrawerToggleText);
    },
    
	selectNetwork: function(event) {
		if(!event.item)
			return;
		
		this.networkListBusy($L("Selecting network"));
	   
	   var name = event.item.networkListName.escapeHTML();
	   this.networkSetReq = TelephonyService.networkSet(false, event.item.networkId, this.onNetworkSet.bind(this, name, event.item.networkId));
	   
	},
	
	onNetworkSet: function(name, id, result) {
		var status = name;
		if (result === true) {
			for(var i=0; i< this.networkList.length; i++) {
	   			this.networkList[i].checkMark = ''
	   			if(this.networkList[i].networkId == id) {
					this.networkList[i].checkMark = 'checkmark';
					this.currentNetworkId = id;
				}
	   		}
	   		this.controller.modelChanged(this.networkListModel);
			this.toggleNetworkListDrawer(false);
			this.automaticSelectionActive = false;
		} else {
			status = Mojo.View.render({
				object: {"errorText":$L("Unable to select network")},
		           template: 'preflist/networkerrorimage'
		      });
		}
		
		this.networkListBusyOff(status);
	},
	
	updateNetworkname: function(payload) {	
		var inService = false;
 		if(payload) {
			if (payload.extended) {
				if(payload.extended.state == 'service') {
					inService = true;
					this.controller.get('networkname').innerHTML = $L(payload.extended.networkName).escapeHTML();
					$('reading_networklist_status').innerHTML = $L(payload.extended.networkName).escapeHTML();
				}
				else if(payload.extended.state == 'limited' && payload.extended.registration == 'denied') {
					$('reading_networklist_status').innerHTML = $L("Unable to connect");
				} else {
					$('reading_networklist_status').innerHTML = $L("View available networks");
				}		
			}
			else if (payload.eventNetwork) {
				if(payload.eventNetwork.state === 'service') {
					this.controller.get('networkname').innerHTML = $L(payload.eventNetwork.networkName).escapeHTML();
					$('reading_networklist_status').innerHTML = $L(payload.eventNetwork.networkName).escapeHTML();
					inService = true;				
				}
				else if(payload.eventNetwork.state === 'limited' && payload.eventNetwork.registration == 'denied' && this.phoneType == "gsm" && !this.toggleNetworkAutoSelectModel.value) {
					$('reading_networklist_status').innerHTML = $L("Unable to connect");
				}
			}
		}
		if(this.callFwdQueryError && inService) 
			this.updateCalls();		
	},
	
	updateManualDataSettings: function(payload) {
		// don't show on CDMA
		if (this.phoneType == 'cdma') {
			return;
		}
		
		if (payload && payload.useThisOverrideRecord === "1") {
			this.toggleManualDataSettingsModel.value = true;
		} else {
			this.toggleManualDataSettingsModel.value = false;
		}
		this.updateManualDataSettingsToggle(this.toggleManualDataSettingsModel.value);
		
		this.controller.modelChanged(this.toggleManualDataSettingsModel);	
	},

	updateManualDataSettingsToggle: function(show) {
		if (show) {
			$('manualdatasettingstogglerow').removeClassName('last');
			$('manualdatasettingsrow').show();
		} else {
			$('manualdatasettingsrow').hide();
			$('manualdatasettingstogglerow').addClassName('last');
		}
	},
	
	updateInternationalDialingSettings: function(payload) {
		if (payload) { 
			
			this.internationalDialingRegionId = payload.phoneInternationalDialingRegionId
			
			if (payload.phoneInternationalDialingActive == true 
				&& InternationalDialingSettings.get([this.internationalDialingRegionId])) {
				this.updateInternationalDialingToggle(true);
				this.internationalDialingModel.value = true;
			} else {
				this.updateInternationalDialingToggle(false);
				this.internationalDialingModel.value = false;
			}
		}
			
		this.controller.modelChanged(this.internationalDialingModel);
	},
	
	updateInternationalDialingToggle: function(show, push) {
		// currently just works in NANP countries
		var region = Mojo.Locale.getCurrentFormatRegion() || '';
		switch (region.substr(-2)) {
			case 'us':
			case 'ca':
				break;
			default:
				$('internationalDialingRegionRow').hide();
				$('internationalDialingInfo').hide();
				$('internationalDialingRow').hide();
				if (this.phoneType == 'gsm') {
					$('callWaitingRow').addClassName('last');
				} else {
					$('calls').hide();
				}
				return;		
		}
		
		if (show) {
			$('internationalDialingRow').removeClassName('last');
			$('internationalDialingRegionRow').show();
			if (push && !(this.internationalDialingRegionId)) {
				this.showInternationalDialingSettings();
			} else if (InternationalDialingSettings.get([this.internationalDialingRegionId])) {
				$('internationalDialingRegion').textContent = InternationalDialingSettings.get(this.internationalDialingRegionId).name;
			}
			$('internationalDialingInfo').show();
		} else {
			$('internationalDialingRegionRow').hide();
			$('internationalDialingRow').addClassName('last');
			$('internationalDialingInfo').hide();
		}
		SystemService.setSystemPreferencesService("phoneInternationalDialingActive", show);
	},
	
	//TTY
    updateTTY: function(payload){
		
		if(!payload.returnValue || !payload.extended)
			return;
        
		if(payload.extended.mode === 'full')
			this.ttyModel.value = true;
		else
			this.ttyModel.value = false;
        
        this.controller.modelChanged(this.ttyModel);
    
		if (payload.extended.mode === 'off') {			
			this.hacModel.disabled = false
		} else {
			this.hacModel.disabled = true;
		}
		
		this.controller.modelChanged(this.hacModel);

	},
	
updateHAC: function(payload){
		
		if(!payload.returnValue || !payload.extended || !payload.extended.available)
			return;
		
		$('ttyRow').removeClassName('single');
		$('ttyRow').addClassName('first');
		$('hacRow').show();   
		 
		if(payload.extended.enabled)
			this.hacModel.value = true;
		else
			this.hacModel.value = false;
        
        this.controller.modelChanged(this.hacModel);
    
		if (payload.extended.enabled) {			
			this.ttyModel.disabled = true
		} else {
			this.ttyModel.disabled = false;
		}
		
		this.controller.modelChanged(this.ttyModel);
		

	},
    
	
	
	//WAN data usage
    updateWAN: function(payload){
		 if(payload.returnValue != undefined)
	 		return;

		if(payload.disablewan == 'on')
			this.toggleWANModel.value = false;
		else if(payload.disablewan == 'off')
			this.toggleWANModel.value = true;
        
        this.controller.modelChanged(this.toggleWANModel);
    },

	//Data Roaming
    updateDataRoaming: function(payload){
		
		//The Preference key may be empty if the device is flashed. WAND guys asked me to assume roamguard is enabled by default.
		if(payload.returnValue != undefined && !payload.returnValue) {
			this.dataRoamingModel.currentDataRoaming = "false";
			this.controller.modelChanged(this.dataRoamingModel);
			return;			
		}		
		if (payload.roamguard && payload.roamguard.roamguard == 'neverblock') {			
             this.dataRoamingModel.currentDataRoaming = "true";
         }
         else {
              this.dataRoamingModel.currentDataRoaming = "false";
         }		
               
        this.controller.modelChanged(this.dataRoamingModel);        
    },
    
	updateRat: function(payload) {
	
		if (payload && payload.extended && payload.extended.mode) {
			this.ratModel.currentRat = payload.extended.mode;
			this.controller.modelChanged(this.ratModel);
		}
		
		if ($("ratRow") && this.hideRatSelection !== true) {
			$("ratRow").show();
		}
	},
	
	updateRatSelection: function(payload) {
		if (payload && payload.hideRatSelection) {
			this.hideRatSelection = true;
			
			if ($("ratRow")) {
				$("ratRow").hide();
			}
		}
	},
    
	
	//Voice Roaming
	voiceRoamingSelect: function(event) {
		if (this.roamingAllowsBandSelection) {
			var band = "";
			var mode = ""; 
			switch (this.voiceRoamingModel.currentVoiceRoaming) {
				case "home":
				case "homeonly":
					band = "home";
					mode = "homeonly";
					break;
				case "class0_A_side":
				case "class0_B_side":
					band = this.voiceRoamingModel.currentVoiceRoaming;
					mode = "any";
				default:
					break;
			}
			
			this.roamModeSetReq = TelephonyService.roamModeSet(mode, band);	
			
		} else {
			this.roamModeSetReq = TelephonyService.roamModeSet(this.voiceRoamingModel.currentVoiceRoaming);	
		}
		
		if(this.voiceRoamingModel.currentVoiceRoaming == "homeonly") {
			this.setRoamguardServiceReq = SystemService.setRoamguardService("false", null);
			this.dataRoamingModel.currentDataRoaming = "false";
			this.controller.modelChanged(this.dataRoamingModel);
			$('dataroamingrow').hide();
		} else {
			$('dataroamingrow').show();
		}
	},
	
    updateVoiceRoaming: function(payload){
		if(!payload.returnValue || !payload.extended)
			return;
        
		if (payload.extended.preferredonly === false) {
			this.roamingAllowsBandSelection = true;
			this.voiceRoamingChoices[1] = {
				label: $L("Automatic - A"),
				value: "class0_A_side"	
			};
			this.voiceRoamingChoices[2] = {
				label: $L("Automatic - B"),
				value: "class0_B_side"  // cdma: the 12" extended remix?
			};
			
			switch (payload.extended.band) {
				case "class0_A_side":
				case "class0_B_side":
					this.voiceRoamingModel.currentVoiceRoaming = payload.extended.band;
					$('dataroamingrow').show();
					break;
				case "home":
				case "homeonly":
					this.voiceRoamingModel.currentVoiceRoaming = "homeonly";
					$('dataroamingrow').hide();
					break;
				default:
					Mojo.Log.error("unknown band. defaulting to home only", payload.extended.band);
					this.voiceRoamingModel.currentVoiceRoaming = "homeonly";
					$('dataroamingrow').hide();
			}
		} else {
			this.roamingAllowsBandSelection = false;
			// if update happens while we are open and band selection
			// was previously allowed (assuming based on choices == 3)
			// put things back
			if (this.voiceRoamingChoices.length == 3) {
				this.voiceRoamingChoices[1] = {
					label: $L("Automatic"),
					value: "any"	
				};
				this.voiceRoamingChoices.pop();
			}
			
			if (payload.extended.mode == 'any') {
				this.voiceRoamingModel.currentVoiceRoaming = "any";
				$('dataroamingrow').show();
			} else {
				this.voiceRoamingModel.currentVoiceRoaming = "homeonly";
				$('dataroamingrow').hide();
			}
		}        
        this.controller.modelChanged(this.voiceRoamingModel);		  
    },

   
    //DIALING SHORTCUTS
    //
    updateDialingShortcuts: function(){
        var i = 1;
        this.dialingShortcutsList.clear();
        while (i <= 10) {
            if (Settings.dialingShortcuts[i]) {
                this.dialingShortcutsList.push({
                    text: i,
                    value: Settings.dialingShortcuts[i] + 'X'.times(i)
                })
            }
            i++;
        }
        this.controller.modelChanged(this.dialingShortcutsModel);
    },
	
	loadDialingShortcuts: function(payload){
		
		this.dialingShortcutsList.clear();
		this.controller.modelChanged(this.dialingShortcutsModel);
        
		if(!payload)
			return;
		
		$H(payload).each(function(pair){			
			if(pair.key && pair.value) {				
				var str = pair.key.sub('DigitNumber','');
				var dispText = $L("#{NUM} digits").interpolate({NUM:parseInt(str)});					
				this.dialingShortcutsList.push({
					value: pair.value + '-' + 'X'.times(parseInt(str)),
                    text: dispText,
					name: pair.key					
                })
			}
		}.bind(this));
		this.controller.modelChanged(this.dialingShortcutsModel);
    },
	
	dialingShortCutAdded: function(obj) {
		if(!obj)
			return;
		
		//Check if it's already defined.		
		var str = obj.text.sub('DigitNumber','');	
		var dispText = $L("#{NUM} digits").interpolate({NUM:parseInt(str)});
		for(var i = 0; i<this.dialingShortcutsList.length; i++) {			
			if(this.dialingShortcutsList[i].name === obj.text) {
				this.dialingShortcutsList[i].value = obj.value + '-' + 'X'.times(parseInt(str));
				this.controller.modelChanged(this.dialingShortcutsModel);
				return;
			}				
		}						
		this.dialingShortcutsList.push({
			value: obj.value + '-' + 'X'.times(parseInt(str)),
            text: dispText, 
			name: obj.text		
         })		
		this.controller.modelChanged(this.dialingShortcutsModel);
	},
    
    addDialingShortcut: function(event){       
        Mojo.Controller.stageController.pushScene('dialingshortcut',this);        
    },
	
	 deleteDialingShortcut: function(event){
        
		this.dialingShortcutsList.splice(event.index,1);
        this.setSystemPreferencesServiceReq = SystemService.setSystemPreferencesService(event.item.name, false);
    },
	
      
    //SECURITY STUFF
	//FDN
    updateFDN: function(payload){		
		if (payload && payload.returnValue === true){//success
	        Settings.fdnOn = (payload.extended.enabled);
		}
        else if(payload && payload.returnValue === false)
			Settings.fdnOn = false;
		
		if (payload && payload.extended && payload.extended.permanentblock) {
			
			this.controller.listen($('fdnwaiting'), Mojo.Event.tap, this.showErrorDialog.bind(this, $L("PIN2 permanently blocked.  Call carrier for replacement SIM.")));
			var errorParams = {
				errorText: $L("PIN2 blocked"),
				errorImage: "images/lock.png"
			}
			var errorImageContent = Mojo.View.render({
			 		object: errorParams,
		           template: 'preflist/pinblocked'
		      });
			$("fdnwaiting").innerHTML = errorImageContent;  
			$("fdn").hide();
			$("setfdn").hide();
		} else {
			$("fdnwaiting").hide();
			$("fdn").show();
			$("setfdn").show();	
		}
		
		if(Settings.fdnOn && !(payload && payload.extended && payload.extended.permanentblock))
			$('changeFDNPIN').show();
		else
			$('changeFDNPIN').hide();
			
		this.fdnModel.value = Settings.fdnOn;
        this.controller.modelChanged(this.fdnModel);
        
    },
	
    updateLockSIM: function(showBanner, payload){

		if (payload && payload.returnValue){
			$('lockSIMwaiting').hide();
			$("lockSIM").show();
			
			if ($('locksim-spinner')) {
				$('locksim-spinner').hide();
			}
			
			Settings.pin1Boot = (payload.extended.enabled);
			
			if (payload.extended.pukrequired) {
				$('lockSIM').innerHTML = $L("PUK Required");
			} else if (payload.extended.simlocked) {
				$('lockSIM').innerHTML = $L("SIM permanently locked");
				$('changeSIMPIN').hide();
			} else if (payload.extended.enabled == true) {
				$('lockSIM').innerHTML = $L("Unlock SIM card");
				$('changeSIMPIN').show();
			} else {
				$('lockSIM').innerHTML = $L("Lock SIM card");
				$('changeSIMPIN').hide();
				if (showBanner === true) {
					Mojo.Controller.appController.showBanner(
				{
					icon: "images/notification-small-handset.png",
					messageText: $L("PIN Disabled"),
					soundClass: 'none'
				}, 
			{},'');
				}
			}
		}
    },

   checkPuk2: function(changepin){
        this.pin2StatusReq = TelephonyService.pin2Status(this.showPin2OrPuk2Box.bind(this, changepin));
   },

	showPin2OrPuk2Box: function(changepin, payload){
		if (payload && payload.returnValue){
			if (payload.extended.pukrequired){//show puk2 box
				PrefSetter.displayPuk2Lock();
			}
			else{//askpin2
				if(changepin == true)
					this.doChangePin2Dialog();
				else
					this.askPin2();				
			}
		}
		else{//ask pin2
			if(changepin == true)
				this.doChangePin2Dialog();
			else
				this.askPin2();
		}
	},

    askPin2: function(callback){
		if (!this.hasPincodeScene) {
			var pincodeArgs = {
				title: [$L("Enter PIN2")],
				pinPages: 1,
				hasCallback: true,
				callbackHandler: this.toggleFDN.bind(this)
			}
			this.controller.stageController.pushScene({
				name: "pincode",
				automaticFocusAdvance: false
			},pincodeArgs);
			this.hasPincodeScene = true;
		}
    },
    
	toggleFDN:function (callback,pin){
		if(Settings.fdnOn==true){
			this.setFixedDialingStatusReq = TelephonyService.setFixedDialingStatus (pin[0], false, this.setFixedDialingCallback.bind(this, false, callback));		
		}
		else{
			this.setFixedDialingStatusReq = TelephonyService.setFixedDialingStatus (pin[0], true, this.setFixedDialingCallback.bind(this, true, callback));		
		}
		this.updateCalls();
	},
	
	setFixedDialingCallback: function(status, callback, payload){
		if(payload && payload.returnValue == true){//success
			Settings.fdnOn = status;
			this.updateFDN();
			callback(true);
		}
		else if(payload && payload.returnValue == false){//failure
	        if (payload.errorCode == 3) {
	            callback(false, "no dial");
				var pincodeArgs = {
					title: [$L("Fixed dialing is enabled"), $L("Enter new PIN2"), $L("Confirm new PIN2")],
					pinPages: 3,
					msg: [$L("Enter PUK2 to reset PIN2"), $L("Enter 4-8 numbers for new PIN2"),$L("Enter 4-8 numbers for new PIN2")],
					callbackHandler: (function(callback, pin){
						PrefSetter.resetPin2(pin, callback)
					}).bind(this)
				}

				Mojo.Controller.stageController.delegateToSceneAssistant('handlePUKParams', pincodeArgs, 2);
        	}
	        else {
				if (Messages.fdnEnableError[payload.errorCode] !== undefined) {
					payload.errorText = Messages.fdnEnableError[payload.errorCode].toString();
				} else {
					payload.errorText = Messages.fdnEnableError[Messages.defaultErrorIndex].toString();
				}
				Mojo.Log.info(payload.errorText);
				if (payload.extended && payload.extended.attemptsRemaining) {
					var str = Mojo.Format.formatChoice(payload.extended.attemptsRemaining, 
					$L("1#one try remaining|##{num} tries remaining"), 
					{num: PrefSetter.numberToWord(payload.extended.attemptsRemaining)});
					callback(false, str);
				}
				else {					
					callback(false, payload.errorText);
				}
            }
		}
	},

    askPin: function(msg){
		if (!this.hasPincodeScene) {
			var pincodeArgs = {
				title: [$L("Enter PIN")],
				pinPages: 1,
				callbackHandler: this.toggleSIMLock.bind(this)
			}
			this.controller.stageController.pushScene({
				name: "pincode",
				automaticFocusAdvance: false
			}, pincodeArgs);
			this.hasPincodeScene=true;
		}
    },
    
    toggleSIMLock: function(callback,pin){
        if (Settings.pin1Boot == true) {            
			this.setPinStatusReq = TelephonyService.setPinStatus(pin[0], false, this.setPinStatusCallback.bind(this,false,callback));
        }
        else {
            this.setPinStatusReq = TelephonyService.setPinStatus(pin[0], true, this.setPinStatusCallback.bind(this,true,callback));
        }
    },
    
	setPinStatusCallback: function(status, callback, payload){
	
                if (payload.returnValue === true) {//success
                    Settings.pin1Boot = status;
			        this.pin1StatusReq3 = TelephonyService.pin1Status(false, this.updateLockSIM.bind(this, true));
                    callback(true);
                }
                else if(payload.returnValue === false){//failure
                    //SIM is now PUK locked
                    if (payload.errorCode == 3) {
						callback(false, "no dial");
						var pincodeArgs = {
							title: [$L("SIM Card PUK Locked"), $L("Enter new PIN"), $L("Confirm new PIN")],
							pinPages: 3,
							msg: [$L("Enter PUK to reset PIN"), $L("Enter 4-8 numbers for new PIN"), $L("Enter 4-8 numbers for new PIN")],
							callbackHandler: (function(callback, pin){
								PrefSetter.resetPin1(pin, callback)
							}).bind(this)
						}
	
						Mojo.Controller.stageController.delegateToSceneAssistant('handlePUKParams', pincodeArgs);
					}
					else {
						if (Messages.enablePinError[payload.errorCode] !== undefined) {
							payload.errorText = Messages.enablePinError[payload.errorCode].toString();
						} else {
							payload.errorText = Messages.enablePinError[Messages.defaultErrorIndex].toString();
						}
						if (payload.extended && payload.extended.attemptsRemaining) {
							var str = Mojo.Format.formatChoice(payload.extended.attemptsRemaining, 
							$L("1#one try remaining|##{num} tries remaining"), 
							{num: PrefSetter.numberToWord(payload.extended.attemptsRemaining)});
							callback(false, str);
						}
						else {
							callback(false, payload.errorText);
						}
					}
                }
	},

    doChangePinDialog: function(){
		if (!this.hasPincodeScene) {
			var pincodeArgs = {
				title: [$L("Enter PIN"), $L("Enter new PIN"), $L("Confirm new PIN")],
				pinPages: 3,
				msg: [$L("Enter old PIN"), $L("Enter 4-8 numbers for new PIN"),$L("Enter 4-8 numbers for new PIN")],
				callbackHandler: this.changePin.bind(this)
			}
			this.controller.stageController.pushScene({
				name: "pincode",
				automaticFocusAdvance: false
			}, pincodeArgs);
			this.hasPincodeScene = true;
		}
    },
    
    changePin: function(callback, pin){
        this.pin1ChangeReq = TelephonyService.pin1Change(pin[0], pin[1], this.pin1ChangeSuccess.bind(this, callback), this.pin1changeFailure.bind(this,callback));
    },
	
	pin1ChangeSuccess: function(callback, payload){
        if (payload.returnValue === true) {
			Mojo.Controller.appController.showBanner(
				{
					icon: "images/notification-small-handset.png",
					messageText: $L("PIN Changed"),
					soundClass: 'none'
				}, 
			{},'');
            callback(true);
        }
        else {
			if (Messages.pinChangeError[payload.errorCode] !== undefined) {
				payload.errorText = Messages.pinChangeError[payload.errorCode].toString();
			} else {
				payload.errorText = Messages.pinChangeError[Messages.defaultErrorIndex].toString();
			}
            callback(false, payload.errorText);
        }
	},    

	pin1changeFailure: function(callback, payload){
        //SIM is now PUK locked
        if (payload.errorCode == 3) {
            callback(false,"no dial");
			var pincodeArgs = {
				title: [$L("SIM Card PUK Locked"), $L("Enter new PIN"), $L("Confirm new PIN")],
				pinPages: 3,
				msg: [$L("Enter PUK to reset PIN "), $L("Enter 4-8 numbers for new PIN"),$L("Enter 4-8 numbers for new PIN")],
				callbackHandler: (function(callback, pin){
					PrefSetter.resetPin1(pin, callback)
				}).bind(this)
			}

			Mojo.Controller.stageController.delegateToSceneAssistant('handlePUKParams', pincodeArgs);
//            PrefSetter.displayPuk1Lock();
        }
        else {
			if (Messages.pinChangeError[payload.errorCode] !== undefined) {
				payload.errorText = Messages.pinChangeError[payload.errorCode].toString();
			} else {
				payload.errorText = Messages.pinChangeError[Messages.defaultErrorIndex].toString();
			}

            if (payload.errorCode == 4) {
                callback(false, payload.errorText);
            }
            else 
                if (payload.extended && payload.extended.attemptsRemaining) {
					var str = Mojo.Format.formatChoice(payload.extended.attemptsRemaining, 
					$L("1#one try remaining|##{num} tries remaining"), 
					{num: PrefSetter.numberToWord(payload.extended.attemptsRemaining)});
					callback(false, str);
                }
                else {
                    callback(false, payload.errorText);
                }	
		}
	},
    
    doChangePin2Dialog: function(){
		if (!this.hasPincodeScene) {
			var pincodeArgs = {
				title: [$L("Enter PIN2"), $L("Enter new PIN2"), $L("Confirm new PIN2")],
				pinPages: 3,
			    msg: [$L("Enter old PIN2"), $L("Enter 4-8 numbers for new PIN2"),$L("Enter 4-8 numbers for new PIN2")],
				callbackHandler: this.changePin2.bind(this),
			}
			this.controller.stageController.pushScene({
				name: "pincode",
				automaticFocusAdvance: false
			}, pincodeArgs);
			this.hasPincodeScene = true;
		}
    },
    
    changePin2: function(callback, pin){
        this.pin2ChangeReq = TelephonyService.pin2Change(pin[0], pin[1], this.pin2ChangeCallback.bind(this, callback));
    },
	
	pin2ChangeCallback: function(callback, payload){
        if (payload && payload.returnValue === true) {
			Mojo.Controller.appController.showBanner(
				{
					icon: "images/notification-small-handset.png",
					messageText: $L("PIN2 Changed"),
					soundClass: 'none'
				}, 
			{},'');
			callback(true);
			
		}
		else if(payload && payload.returnValue === false){
			if (payload.errorCode == 3) {
				callback(false, "no dial");
//				this.controller.stageController.popScene();
				var pincodeArgs = {
					title: [$L("Fixed dialing is enabled"), $L("Enter new PIN2"), $L("Confirm new PIN2")],
					pinPages: 3,
					msg: [$L("Enter PUK2 to reset PIN2"), $L("Enter 4-8 numbers for new PIN2"),$L("Enter 4-8 numbers for new PIN2")],
					callbackHandler: (function(callback, pin){
						PrefSetter.resetPin2(pin, callback)
					}).bind(this)
				}

				Mojo.Controller.stageController.delegateToSceneAssistant('handlePUKParams', pincodeArgs, 2);

//				PrefSetter.displayPuk2Lock();
			}
			else{ 
				if (Messages.pinChangeError[payload.errorCode] !== undefined) {
					payload.errorText = Messages.pinChangeError[payload.errorCode].toString();
				} else {
					payload.errorText = Messages.pinChangeError[Messages.defaultErrorIndex].toString();
				}
			
				if (payload.extended && payload.extended.attemptsRemaining) {
					var str = Mojo.Format.formatChoice(payload.extended.attemptsRemaining, 
					$L("1#one try remaining|##{num} tries remaining"), 
					{num: PrefSetter.numberToWord(payload.extended.attemptsRemaining)});
					callback(false, str);
				}
				else {
					callback(false, payload.errorText);
				}
			}
		}
	},
	
    showFDNList: function(){
        Mojo.Controller.stageController.pushScene('fdn');
    },

	showManualDataSettings: function() {
		Mojo.Controller.stageController.pushScene('datasettings');
	},
	
	showInternationalDialingSettings: function() {
		Mojo.Controller.stageController.pushScene('intldialing', {
			regionId: this.internationalDialingRegionId
		});
	},
    
    doTap: function(event){
        var id = $(event.target).getAttribute("id");
              
        switch (id) {
            case 'lockSIM':{
				//check if puklock is enable
				this.checkPuk1();
            }
break;
            case 'changePin1':{
				this.checkPuk1(true);
            }
break;
			case 'changeFDNPIN':
			case 'changePin2':{
				this.checkPuk2(true);
				break;
			}
		    case 'editFDN':{
                this.showFDNList();
            }
break;
            
			case 'user-provisioning':{
				if (this.provisionRequest == undefined) {//no provisioning service
					this.doDialog($L("Provisioning service is not available, please try later"), "");
				}
				else{
					if (this.UserWaitingForTimeout ==true){
						if (this.hasCheckmark == true)
							this.restoreProvision("User", "checkmark");
						else
							this.restoreProvision("User");
					}
					else if (this.cancelable == true) {
						if (!(this.PRLCancelRestoreProvisionTimeout || this.UserCancelRestoreProvisionTimeout || this.restoreProvisionTimeout)) {
							if (this.userProvisionTaped) 
								this.cancelUserProvisionRequest();
						}
					}
					else{ 
						if (this.cancelable == undefined) {
							this.userProvisionTaped = true;
							this.updateUserProvision();
						}
					}
				}
				break;
			}
			case 'PRL-provisioning':{
				if (this.provisionRequest == undefined) {//no provisioning service
					this.doDialog($L("Provisioning service is not available, please try later"), "");
				}
				else {
					if (this.PRLWaitingForTimeout ==true){
						if (this.hasCheckmark == true)
							this.restoreProvision("PRL", "checkmark");
						else
							this.restoreProvision("PRL");
					}
					else if (this.cancelable == true) {
						if (!(this.PRLCancelRestoreProvisionTimeout || this.UserCancelRestoreProvisionTimeout || this.restoreProvisionTimeout)) {
							if (this.PRLTaped) 
								this.cancelPRLProvisionRequest();
						}
					}
					else {
						if (this.cancelable == undefined) {
							this.PRLTaped = true;
							this.updatePRLProvision();
						}
					}
				}
				break;
			}
			case 'manualdatasettings': {
				this.showManualDataSettings();
				break;
			}
			case 'internationaldialinglabel':
			case 'internationalDialingRegion':
			case 'internationalDialingRegionRow': {
				this.showInternationalDialingSettings();
				break;
			}
            default:
                {
                
                }
        }
        
    },
    
   checkPuk1: function(changePin){
   		this.showedPin = false;
       	this.pin1StatusReq2 = TelephonyService.pin1Status(false, this.showPin1OrPuk1Box.bind(this, changePin));
   },

	showPin1OrPuk1Box: function(changePin, payload){
		if (payload && payload.returnValue){
            Settings.pin1Boot = (payload.extended.enabled);
			
			if (payload.extended.simlocked) {
				this.showErrorDialog($L("SIM permanently locked.  Call carrier for replacement."));
			} else if (payload.extended.pukrequired){//show puk1 box
				if (!this.showedPin) {
					PrefSetter.displayPuk1Lock();
					this.showedPin = true;
				}				
			} else {//show pin1 box or chang pin1
				if(changePin == true){
					this.doChangePinDialog();
				}
				else if (!this.showedPin) {
					this.showPin1Box();
					this.showedPin = true;
				}				
			}
		} else {// show pin1 box
			if(changePin == true){
				this.doChangePinDialog();
			}
			else if (!this.showedPin) {
				this.showPin1Box();
				this.showedPin = true;
			}
		}
	},
	
	showPin1Box: function(){
		if (Settings.pin1Boot == true)
			this.askPin("");
		else
           	this.askPin($L("Upon successful entry of your PIN, SIM lock will take effect after you go in and out of flight mode."));
	},

    doPropertyChanged: function(propertyChange, id){
        var value = propertyChange.value;
        
        switch (id) {
			case 'showContactMatch':
   	            this.setSystemPreferencesServiceReq = SystemService.setSystemPreferencesService('showcontactmatch',value,null);
				break;
            case 'showOutgoingCallerID':
                this.clirSetReq = TelephonyService.clirSet(!value, this.handleError.bind(this));
            	break;            
            case 'callWaiting':
                this.callWaitingSetReq = TelephonyService.callWaitingSet(value,this.handleError.bind(this));
            	break;            
			 case 'toggleRat':
                this.toggleRatReq = TelephonyService.ratSet(value,this.handleError.bind(this));
            	break;            
            case 'fdn':{
				this.updateFDN();
                //this.askPin2();
				this.checkPuk2();
            }
				break;
            
            case 'toggleHAC':
                this.hacSetReq = TelephonyService.hacSet(value, null);
				this.ttyModel.disabled = value;
				this.controller.modelChanged(this.ttyModel);
            	break;
            
			case 'toggleTTY':
                this.ttySetReq = TelephonyService.ttySet(value ? 'full' : 'off',null);
            	this.hacModel.disabled = value;
				this.controller.modelChanged(this.hacModel);
				break;
            
			
            case 'toggleWAN':
                this.wanSetReq = SystemService.setWANService(value ? 'off':'on', null);
            	break;
            
            case 'toggleNetworkAutoSelect':
                if (value == false) {
					$('networknamerow').hide();
                    this.networkListPrompt();
                }
                else {
                   TelephonyService.networkListQueryCancel();
				   this.networkSetReq =  TelephonyService.networkSet(true, 0, null);
				   this.automaticSelectionActive = true;
				   if(this.networkListQueryReq)
				   	this.networkListQueryReq.cancel();
                   this.networkDetailsdrawer.mojo.setOpenState(false);
				   this.controller.hideWidgetContainer(this.networkDetailsdrawer);
				   $('reading_networklist_row').hide();
				   $('networknamerow').show();				 	
                }
            	break;
            
            case 'toggleDataRoaming':
                this.setRoamguardServiceReq = SystemService.setRoamguardService(value, null);            
				break;
			case 'toggleManualDataSettings':
				SystemService.enableManualDataSettings(value);
				this.updateManualDataSettingsToggle(value);
				break;
			case 'toggleVoiceRoaming':
				this.voiceRoamingSelect();
				break;
			case 'callfwd':
				if(value == false) {
					 this.forwardRegisterReq = TelephonyService.forwardRegister('unconditional', '', this.callFwdSet.bind(this));
					$('callfwdlastrow').hide();
					this.controller.hideWidgetContainer(this.controller.get('callfwdlastrow'));
				}               		
				else {
					$('callfwdlastrow').show();
					this.controller.showWidgetContainer(this.controller.get('callfwdlastrow'));
					$('callforward-number').mojo.focus();
					if(this.callFWDNumbermodel.number)
						this.forwardRegisterRequest = TelephonyService.forwardRegister('unconditional', this.callFWDNumbermodel.number, this.callFwdSet.bind(this));
				}					            
				break;
			case 'internationalDialingToggle':
				this.updateInternationalDialingToggle(value, true /* push scene if none selected */);
				break;
        }
    },
	
	handleError: function(payload) {
		
		//If it's success, no need to show the error dialog.
		if(payload.returnValue)
			return;
			
		if (Messages.serviceErrors[payload.errorCode] !== undefined) {
			payload.errorText = Messages.serviceErrors[payload.errorCode].toString();
		}
		else {
			payload.errorText = Messages.serviceErrors[Messages.defaultErrorIndex].toString();
		}
		
		this.showErrorDialog(payload.errorText);
	},

	updateUserProvision: function(){
		this.updateUserProvisionReq = new Mojo.Service.Request('palm://com.palm.provisioning/User', {});
		$('user-provisioning').innerHTML = $L("Cancel update");
		this.spinnerProvisioningModel.spinning = true;
		this.controller.modelChanged(this.spinnerProvisioningModel);
		this.cancelable = true;
	},

	updatePRLProvision: function(){
		this.updatePRLProvisionReq = new Mojo.Service.Request('palm://com.palm.provisioning/PRL', {});
		$('PRL-provisioning').innerHTML = $L("Cancel update");
		this.spinnerPRLModel.spinning = true;
		this.controller.modelChanged(this.spinnerPRLModel);
		this.cancelable = true;
	},
	
	cancelUserProvisionRequest:function(){
		this.cancelUserProvisionReq =  new Mojo.Service.Request('palm://com.palm.omadm/Cancel', {});
		this.cancelUserProvisionReq2 =  new Mojo.Service.Request('palm://com.palm.provisioning/Cancel', {});
		$('user-provisioning').innerHTML = $L("Update canceled");
		if ($('PRL-spinner')) {
			this.spinnerProvisioningModel.spinning = false;
			this.controller.modelChanged(this.spinnerProvisioningModel);
		}
		this.UserWaitingForTimeout = true;
		if(this.UserCancelRestoreProvisionTimeout)
			window.clearTimeout(this.UserCancelRestoreProvisionTimeout);
		this.UserCancelRestoreProvisionTimeout = window.setTimeout(this.restoreProvision.bind(this, "User"), 5000);
	},
 
	cancelPRLProvisionRequest:function(){
		
		this.cancelPRLProvisionReq = new Mojo.Service.Request('palm://com.palm.omadm/Cancel', {});
		this.cancelPRLProvisionReq2 = new Mojo.Service.Request('palm://com.palm.provisioning/Cancel', {});
		$('PRL-provisioning').innerHTML = $L("Update canceled");
		if ($('PRL-spinner')) {
			this.spinnerPRLModel.spinning = false;
			this.controller.modelChanged(this.spinnerPRLModel);
		}
		this.PRLWaitingForTimeout = true;
		if(this.PRLCancelRestoreProvisionTimeout)
			window.clearTimeout(this.PRLCancelRestoreProvisionTimeout);
		this.PRLCancelRestoreProvisionTimeout = window.setTimeout(this.restoreProvision.bind(this, "PRL"), 5000);
	},

   	provisioningStatusSubscribe: function(){
		
       	if (this.provisionRequest !== undefined)
				this.provisionRequest.cancel();
			this.provisionRequest = new Mojo.Service.Request("palm://com.palm.provisioning/SessionStatus", {
				parameters: {
					'subscribe': true
				},
				onSuccess: this.onProvisionSessionStatusSuccess.bind(this),
				onFailure: this.onProvisionSessionStatusFailure.bind(this)
			});
    },
	
   	onProvisionSessionStatusSuccess: function(payload){
		
		if(payload.status){	
			switch (payload.status.toLowerCase()) {
				case 'noupdate':
					$('PRL-provisioning').innerHTML = $L("No PRL update available");
					$("PRL-label").addClassName('checkmark');
					this.hasCheckmark = true;
					if ($('PRL-spinner')) {
						this.spinnerPRLModel.spinning = false;
						this.controller.modelChanged(this.spinnerPRLModel);
					}
					if(this.restoreProvisionTimeout)
						window.clearTimeout(this.restoreProvisionTimeout);
					this.restoreProvisionTimeout = window.setTimeout(this.restoreProvision.bind(this, "PRL", 'checkmark'), 5000);
					this.PRLWaitingForTimeout = true;
					break;
				case 'waiting':
				case 'busy':
					this.cancelable = payload.cancelable;
					break;
				case 'success':
					if (payload.trigger == "PRL") {
						$('PRL-provisioning').innerHTML = $L("PRL updated");
						$('PRL-label').addClassName('checkmark');
						this.hasCheckmark = true;
						
						if ($('PRL-spinner')) {
							this.spinnerPRLModel.spinning = false;
							this.controller.modelChanged(this.spinnerPRLModel);
						}
						this.PRLWaitingForTimeout = true;
					}
					else if(payload.trigger == "User"){
						$('user-provisioning').innerHTML = $L("Settings updated");
						$('user-label').addClassName('checkmark');
						this.hasCheckmark = true;
						if ($('user-spinner')) {
							this.spinnerProvisioningModel.spinning = false;
							this.controller.modelChanged(this.spinnerProvisioningModel);
						}
						this.UserWaitingForTimeout = true;
					}
					//show check mark
					if(this.restoreProvisionTimeout)
						window.clearTimeout(this.restoreProvisionTimeout);
					this.restoreProvisionTimeout = window.setTimeout(this.restoreProvision.bind(this, payload.trigger, 'checkmark'), 5000);
					break;
				case 'failure':
					this.cancelable = undefined;
					
					var errMsg;
					if (payload.trigger == "PRL") {
						this.PRLTaped = undefined;
						$('PRL-provisioning').innerHTML = $L("Update PRL");
						if ($('PRL-spinner')) {
							this.spinnerPRLModel.spinning = false;
							this.controller.modelChanged(this.spinnerPRLModel);
						}
						errMsg = $L("The PRL update could not be completed. Try again later. If the problem persists, call #{carrier} Customer Service.").interpolate({carrier:this.carrier});
					}
					else if (payload.trigger == "User")
					{
						this.userProvisionTaped = undefined;
						$('user-provisioning').innerHTML = $L("Update network settings");
						if ($('user-spinner')) {
							this.spinnerProvisioningModel.spinning = false;
							this.controller.modelChanged(this.spinnerProvisioningModel);
						}
						errMsg = $L("The network settings could not be updated. Try again later. If the problem persists, call #{carrier} Customer Service.").interpolate({carrier:this.carrier});
					}
					this.doDialog(errMsg, payload.errorCode);
					break;
				default:
					break;
			}
		}		
	},
   	onProvisionSessionStatusFailure: function(payload){
		
		if (payload.status && payload.status.toLowerCase() == "failure") {
			this.cancelable = undefined;
			
			var errMsg;
			if (payload.trigger == "PRL") {
				this.PRLTaped = undefined;
				$('PRL-provisioning').innerHTML = $L("Update PRL");
				if ($('PRL-spinner')) {
					this.spinnerPRLModel.spinning = false;
					this.controller.modelChanged(this.spinnerPRLModel);
				}
				errMsg = $L("The PRL update could not be completed. Try again later. If the problem persists, call #{carrier} Customer Service.").interpolate({carrier:this.carrier});
			}
			else if (payload.trigger == "User")
			{
				this.userProvisionTaped = undefined;
				$('user-provisioning').innerHTML = $L("Update network settings");
				if ($('user-spinner')) {
					this.spinnerProvisioningModel.spinning = false;
					this.controller.modelChanged(this.spinnerProvisioningModel);
				}
				errMsg = $L("The network settings could not be updated. Try again later. If the problem persists, call #{carrier} Customer Service.").interpolate({carrier:this.carrier});
			}
			this.doDialog(errMsg,payload.errorCode);
		}
		else if(payload.serviceName == "com.palm.provisioning" && payload.returnValue == false){
			if (this.provisionRequest !== undefined)
				this.provisionRequest.cancel();
			this.provisionRequest = undefined;
		}
		else {
			this.cancelable = undefined;
			this.PRLTaped = undefined;
			this.userProvisionTaped = undefined;
			$('PRL-provisioning').innerHTML = $L("Update PRL");
			$('user-provisioning').innerHTML = $L("Update network settings");
		}
	},

	restoreProvision:function(type, classname){
		
		if (this.PRLCancelRestoreProvisionTimeout) {
			window.clearTimeout(this.PRLCancelRestoreProvisionTimeout);
			this.PRLCancelRestoreProvisionTimeout = undefined;
			$('PRL-provisioning').innerHTML = $L("Update PRL");
			if(classname !== undefined)
				$('PRL-label').removeClassName(classname);
		}
		
		if(this.UserCancelRestoreProvisionTimeout){
			window.clearTimeout(this.UserCancelRestoreProvisionTimeout);
			this.UserCancelRestoreProvisionTimeout = undefined;
			$('user-provisioning').innerHTML = $L("Update network settings")
			if(classname !== undefined)
				$('user-label').removeClassName(classname);
			
		}			
		if (this.restoreProvisionTimeout) {
			window.clearTimeout(this.restoreProvisionTimeout);
			this.restoreProvisionTimeout = undefined;
		
			if (type == "PRL") {
				$('PRL-provisioning').innerHTML = $L("Update PRL");
				if(classname !== undefined)
					$('PRL-label').removeClassName(classname);
			}
			else {
				$('user-provisioning').innerHTML = $L("Update network settings")
				if(classname !== undefined)
					$('user-label').removeClassName(classname);
			}
		}
		this.cancelable = undefined;
		this.PRLTaped = undefined;
		this.userProvisionTaped = undefined;
		this.PRLWaitingForTimeout = false;
		this.UserWaitingForTimeout = false;

	},


	doDialog: function(messages, errorCode) {
		
		this.controller.showDialog({
			template: 'provisioning/provisioning-dialog',
			assistant: new ProvisionDialogAssistant(this),
			message: messages,
			errorcode: errorCode
		});
		
	},

initOnProvisionStart: function() {
	
	// Register to receive a callback when the service starts
	this.serverStatusReq = new Mojo.Service.Request('palm://com.palm.bus/signal/', {
		method: 'registerServerStatus',
		parameters: {'serviceName':"com.palm.provisioning"},
		onSuccess: this.handleProvisionServerStatus.bind(this)
	});
},

handleProvisionServerStatus: function(payload) {
	if (payload.connected == true)
		this.provisioningStatusSubscribe();
	else{//provision is down
		if (this.provisionRequest !== undefined)
			this.provisionRequest.cancel();
		this.provisionRequest = undefined;
	}
},

handleTapOnVoicemailReset: function(event) {
	if(!event)
		return;
		
	TelephonyService.voicemailReset();
},

handleExternalLaunch: function(args){//type, callingapp, number, closeapp){
	Mojo.Log.info("PreflistAssistant::handleExternalLaunch type: "+args.type);
        switch (args.type) {
            case 'deviceLock':
				if (!this.hasPincodeScene) {
					var titleText;
					var msgText;
					if (args.unblock == true) {
						titleText = $L("Enter Unblock Code");
						msgText = $L("Contact your carrier for the unblock code")
					}
					else {
						titleText = $L("Enter Network Unlock Code");
						msgText = $L("Contact your carrier for the unlock code")
					}
					var pincodeArgs = {
						maxLength: 16,
						title: [titleText],
						msg:[msgText],
						pinPages: 1,
						closeapp: args.closeapp,
						callingapp: args.callingapp,
						callbackHandler: (function(callback, pin){
							PrefSetter.deviceLockUnlock(pin[0], args.locktype, args.unblock, callback);
						}).bind(this)
					}
					this.controller.stageController.pushScene({
				name: "pincode",
				automaticFocusAdvance: false
			}, pincodeArgs);
					this.hasPincodeScene = true;
				}
				break;
    		case 'unlockTelephony':
				if (!this.hasPincodeScene) {
					var pincodeArgs = {
						title: [$L("SIM Card Locked")],
						msg: [$L("Enter PIN")],
						pinPages: 1,
						closeapp: args.closeapp,
						callingapp: args.callingapp,
						callbackHandler: (function(callback, pin){
							PrefSetter.unlockTelephony(pin, callback)
						}).bind(this)
					}
					this.controller.stageController.pushScene({
				name: "pincode",
				automaticFocusAdvance: false
			}, pincodeArgs);
					this.hasPincodeScene = true;
				}
					break;
            case 'pin1Reset':
					if (!this.hasPincodeScene) {
						var pincodeArgs = {
							title: [$L("Enter PUK code"), $L("Enter new PIN"), $L("Confirm new PIN")],
							pinPages: 3,
							number: args.number,
							msg: [$L("Enter PUK to reset PIN"), $L("Enter 4-8 numbers for new PIN"),$L("Enter 4-8 numbers for new PIN")],
							closeapp: args.closeapp,
							callingapp: args.callingapp,
							callbackHandler: (function(callback, pin){
								PrefSetter.resetPin1(pin, callback)
							}).bind(this)
						}
						this.controller.stageController.pushScene({
				name: "pincode",
				automaticFocusAdvance: false
			}, pincodeArgs);
						this.hasPincodeScene = true;
					}
				break;
            case 'pin2Reset':
				if (!this.hasPincodeScene) {
					var pincodeArgs = {
						title: [$L("Enter PUK2"), $L("Enter new PIN2"), $L("Confirm new PIN2")],
						pinPages: 3,
						number: args.number,
						msg: [$L("Enter PUK2 to reset PIN2"), $L("Enter 4-8 numbers for new PIN2"),$L("Enter 4-8 numbers for new PIN2")],
						closeapp: args.closeapp,
						callingapp: args.callingapp,
						callbackHandler: (function(callback, pin){
							PrefSetter.resetPin2(pin, callback)
						}).bind(this)
					}
					this.controller.stageController.pushScene({
				name: "pincode",
				automaticFocusAdvance: false
			}, pincodeArgs);
					this.hasPincodeScene = true;
				}
				break;
            case 'fdnDisable':
				if (!this.hasPincodeScene) {
					var pincodeArgs = {
						title: [$L("Fixed dialing is enabled")],
						pinPages: 1,
						number: args.number,
						msg: [$L("Enter PIN2")],
						closeapp: args.closeapp,
						callingapp: args.callingapp,
						callbackHandler: this.toggleFDN.bind(this)
					}
					this.controller.stageController.pushScene({
				name: "pincode",
				automaticFocusAdvance: false
			}, pincodeArgs);
					this.hasPincodeScene = true;
				}
				break;
			case 'setApn':
				this.controller.stageController.pushScene({
						name: "datasettings"
					}, {
						callingapp: args.callingapp,
						category: args.category
					});
				break;
			case 'startNetworkSearch':					
					this.loadNetworkList.bind(this).delay(5);
					break;
			case 'refresh':
					SystemService.getSystemPreferencesService(['phoneInternationalDialingActive', 'phoneInternationalDialingRegionId'],
						this.updateInternationalDialingSettings.bind(this));
					break;
			default:
				break;            
        }
},
            

    // Options for list selector choices:
    dtmfTones: [{
        label: $L('Short'),
        value: "false"
    }, {
        label: $L('Long'),
        value: "true"
    }],
    
    dtmfTonesModel: {
        currentTone: "false"
    },
	
	dataRoamingChoices: [
		{
			label: $L("Enabled"),
			value: "true"
		},
		{
			label: $L("Disabled"),
			value: "false"
		}
	],
	
	dataRoamingModel: {
		currentDataRoaming: "false"
	},
	
	


});
var ProvisionDialogAssistant = Class.create({
	
	initialize: function(sceneAssistant) {
		this.sceneAssistant = sceneAssistant;
		this.controller = sceneAssistant.controller;
	},
	
	setup : function(widget) {
		this.widget = widget;
		this.controller.get('okButton').addEventListener(Mojo.Event.tap, this.handleOK.bindAsEventListener(this));
	},
	
	handleOK: function() {
		this.widget.mojo.close();
	}
});





